package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

// 记录日志操作的切面类
@Slf4j
@Component
@Aspect
public class OperatorLogAspect {
    // HttpServletRequest是SpringIOC容器中的Bean, 直接注入即可
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;

    // 1.定义切入点表达式
    // 2.定义通知
    @Around("@annotation(com.itheima.anno.Log)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        // 操作人的id 需要拿到Request对象, 拿到token请求头, 才能拿到操作人的id
        String token = request.getHeader("token");

        Integer operateEmpId = 0;
        if (token != null) {
            Claims claims = JwtUtils.parseJWT(token);
            operateEmpId = (Integer) claims.get("id");
        }

        // 操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        // 目标方法所在类名
        String className = pjp.getTarget().getClass().getName();
        // 目标方法名
        String methodName = pjp.getSignature().getName();
        // 目标方法的参数
        Object[] args = pjp.getArgs();
        String methodParams = Arrays.toString(args);
        long begin = System.currentTimeMillis();
        // 目标方法的返回值
        Object ret = pjp.proceed();
        long end = System.currentTimeMillis();

        String retValue = "";
        if (ret != null) {
            retValue = ret.toString();
        }

        // 目标方法的执行时间
        long costTime = end - begin;
        // 把数据保存到对象中
        OperateLog operateLog = new OperateLog(
                null, operateEmpId, operateTime, className, methodName,
                methodParams, retValue, costTime, null);
        // 调用Mapper保存到数据库
        operateLogMapper.insert(operateLog);
        return ret;
    }
}
